#!/bin/sh
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"

if [ -z "$LMD_APPS_DIR" ]; then
   echo "Error: Env LMD_APPS_DIR is not defined."
   exit 1
else 
   echo "Env LMD_APPS_DIR: "$LMD_APPS_DIR
fi

export CURRENT_APP_PATH="${LMD_APPS_DIR}/mediainfo"
mkdir -p "$CURRENT_APP_PATH"
if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

source "$LMD_BASE_INSTALL_SCRIPT_DIR/apps/mediainfo/env_read.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/download_utils.sh"

install_for_mac() {
    INSTALLER_URL=$_MAC_DOWNLOAD_URL
    INSTALLER_FILE_PATH="$CURRENT_APP_PATH/${_MAC_INSTALLER_FILE_NAME}"
    echo "url: "$INSTALLER_URL
    echo "lmdprogress:20"
    download_with_resume "$INSTALLER_FILE_PATH" "$INSTALLER_URL"
    echo "downloaded."
    cd "$CURRENT_APP_PATH"

    echo "lmdprogress:50"

    echo "check "$_MAC_INSTALL_TARGET_FILE_NAME
    INSTALL_TARGET_FULL_PATH="$_MAC_INSTALL_PATH/$_MAC_INSTALL_TARGET_FILE_NAME"
    if [ -d "$INSTALL_TARGET_FULL_PATH" ];then
        echo "$INSTALL_TARGET_FULL_PATH found. Remove it."
        rm -rf "$INSTALL_TARGET_FULL_PATH"
    else
        echo "$INSTALL_TARGET_FULL_PATH not found."
    fi

    MOUNT_APP_PATH="/Volumes/MediaInfo"
    # mount .dmg file
    hdiutil attach "$INSTALLER_FILE_PATH" -mountpoint $MOUNT_APP_PATH -nobrowse

    echo "lmdprogress:55"

    if [ ! -d "$_MAC_INSTALL_PATH" ]; then
        echo "Error: $_MAC_INSTALL_PATH dose not exist"
        exit 1
    fi

    cd "$_MAC_INSTALL_PATH"
    echo "copy to target dir"
    # cp -r "$MOUNT_APP_PATH/$_MAC_INSTALL_TARGET_FILE_NAME" "$_MAC_INSTALL_PATH"
    ditto "$MOUNT_APP_PATH/$_MAC_INSTALL_TARGET_FILE_NAME" "$_MAC_INSTALL_PATH/$_MAC_INSTALL_TARGET_FILE_NAME"

    echo "lmdprogress:75"
    echo "detach image"
    hdiutil detach $MOUNT_APP_PATH
    
    echo "lmdprogress:90"
}

install_for_win() {
    INSTALLER_URL=$_WINDOWS_X64_DOWNLOAD_URL
    INSTALLER_FILE_PATH="$CURRENT_APP_PATH/${_WINDOWS_X64_INSTALLER_FILE_NAME}"
    echo "start download: "$INSTALLER_URL
    echo "lmdprogress:30"
    download_with_resume "$INSTALLER_FILE_PATH" $INSTALLER_URL 'allow' 3242880
    
    echo "lmdprogress:80"
    echo "downloaded."

    source "$LMD_BASE_INSTALL_SCRIPT_DIR/global/install_7z.sh"
    7zr x "$INSTALLER_FILE_PATH" -o"$CURRENT_APP_PATH/install_dir" -y
}

echo "lmdprogress:15"
if [ -f /etc/os-release ]; then
   echo "Linux system."
   echo "Not supported."
   exit 1
elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
   echo "macOS system."
   install_for_mac
elif current_os_is_windows; then
   echo "Windows system."
   install_for_win
else
   echo "Unknown OS"
fi


echo "lmdprogress:100"




